
package managedbean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.CustomerJPA;
import ejb.CustomerFacadeRemote;
import ejb.CustomerFacade;

/**
 * Managed Bean AddClientMBean
 */
@ManagedBean(name = "customerRegister")
@SessionScoped
public class AddClientMBean implements Serializable{
	
	
	private static final long serialVersionUID = 1L;

	@EJB
	private CustomerFacadeRemote customerRemote;
	
	protected CustomerJPA dataCustomer = new CustomerJPA();
	protected String date=" ";
	protected String pwd2;
	
	public AddClientMBean() throws Exception{
		setCustomer();
	}
	
	public CustomerJPA getDataCustomer()
	{
		return dataCustomer;
	}	
	public void setDataCustomer(CustomerJPA customer)
	{
		this.dataCustomer=customer;
	}
	public String getPwd2(){
		return pwd2;
	}
	public void setPwd2(String pwd2){
		this.pwd2 = pwd2;
	}
	public String getDate(){
		return date;
	}
	public void setDate(String date){
		this.date = date;
	}
	public String index(){
		return "homeView";
	}

 	public void setCustomer() throws Exception{
 		dataCustomer = new CustomerJPA();
 	}
 	
 	/**
	 * Method to prepare data before adding client
	 */
	public String addClientMBean() throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
		dataCustomer.setBirthdate(sdf.parse(date));
		dataCustomer.setAdministrator(false);
		if(dataCustomer.getPassword().equals(this.getPwd2())){
			try{
				register();
				FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("loginController", dataCustomer);
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Register successful for user with e-mail "+dataCustomer.getEmail()+". Please, log in now.", null);
				FacesContext.getCurrentInstance().addMessage(null, msg);
				dataCustomer = new CustomerJPA();
				return "homeView";
			}catch (Exception e){
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please, review data introduced.", null);
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
		} else {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Passwords introduced do not match.", null);
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
		return "modifyClientView";
	}
	
	/**
	 * Method to add client
	 */
	public void register() throws Exception{
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		customerRemote = (CustomerFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/CustomerFacadeBean!ejb.CustomerFacadeRemote");
		customerRemote.register(dataCustomer);
	}

}
